<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;
use App\Models\CommonModel;
use App\Models\HomeModel;
use App\Models\UserModel;
use Illuminate\Http\Request;
use App\Libary\Captcha\Code;
use Mail;

// require_once '../app/libary/captcha/Code.class.php';

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('guest', ['except' => 'logout']);
    }

    // public function index(){
    //     // print_r(session('admin'));exit;
        
    //     $meun = LoginModel::getMeun(['pid'=>0]);

    //     return view('backstage/index',['meun'=>$meun]);
    // }
    
    // public function login(){
    //     return view('home/index/login');
    // }

    public function userLogin(){

        if( Input::all() ){
            $data = Input::all();
            $code = new Code;
            $_code =  $code->get();
            // dd(111);
            if( strtoupper( $data['code'] ) != $_code ){
                return response()->json(['res'=>'0','msg'=>'驗證碼輸入錯誤！請重新輸入驗證碼！']);
            }
            if( empty( $data['name'] ) || empty($data['password']) ){
                return response()->json(['res'=>'0','msg'=>'請輸入用護名，或密碼！']);
            }
            $uname = trim($data['name']);
            if( is_email($uname) ){
                $userInfo = HomeModel::getOneUser(['user_email'=>$uname]);
            }else{
                $userInfo = HomeModel::getOneUser(['user_name'=>$uname]);
            }
            


            if(  $userInfo =='' ){
                return response()->json(['res'=>'0','msg'=>'帳號不存在，請重新輸入！']);
            }

            if( $userInfo->user_pass !=  md5(base64_encode(trim( $data['password'] )) ) ){
                return response()->json(['res'=>'0','msg'=>'用護名或密碼輸入不正確，請重新輸入！']);
            }
            session(['user'=>$userInfo]);
            // dd(session('user'));exit;
            // dd(session('user')->id);exit;
            // return redirect('backstage/index');
            $login_type = config('app.login_type');
            $uid = session('user')->id;
            $ip = $_SERVER['REMOTE_ADDR'];
            $type = 1;
            $operation = $login_type[$type];
            $bz = '登錄成功';

            $res = userLog($uid, $ip, $operation, $bz, $type);//登錄日誌
            // dd($res);
            return response()->json(['res'=>'1','msg'=>'登錄成功！','jumpUrl'=>'/user/index']);
        }
        
    }

    // 用戶註冊
    public function userRegister(Request $request){
        // dd(Session::get('code'));
        // dd(Input::all() );
       if( $request->input() ){
            $data = $request->input();
            $_code = Session::get('code');
            // dd($_code);
            // $code = new Code;
            // $_code =  $code->get();
            $count1 = CommonModel::getCount('user',['user_name'=>$data['name']]);
            $count2 = CommonModel::getCount('user',['user_email'=>$data['email']]);
            if(  $count1 > 0 ){
                return response()->json(['res'=>'0','msg'=>'用戶名已被使用！']);
            }
            if(  $count2 > 0 ){
                return response()->json(['res'=>'0','msg'=>'郵箱已被使用，請換壹個試試！']);
            }
            $peg = is_verify(trim($data['email']),$data['code'],1,1800);
            if( $peg == false ){
                return response()->json(['res'=>'0','msg'=>'驗證碼輸入錯誤！請重新輸入驗證碼！']);
            }
            if( empty($data['name']) ){
                return response()->json(['res'=>'0','msg'=>'請輸入用護名！']);
            }elseif(strlen($data['name'])<4 || strlen($data['name'])>20){
                return response()->json(['res'=>'0','msg'=>'請輸入4-20個字符作為用戶名！']);
            }
            if( empty($data['pwd']) ){
                return response()->json(['res'=>'0','msg'=>'請輸入密碼！']);
            }elseif(strlen($data['pwd'])<6 || strlen($data['pwd'])>20){
                return response()->json(['res'=>'0','msg'=>'請輸入6-20個字符作為密碼！']);
            }
            if( empty($data['pwd'])!=empty($data['repwd'])){
                return response()->json(['res'=>'0','msg'=>'兩次輸入的密碼不壹致！']);
            }
            // $emailreg = '/^([a-zA-Z0-9]+[-|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[-|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/';
            if(!is_email($data['email'])){
                return response()->json(['res'=>'0','msg'=>'郵箱輸入不正確']);
            }
            $user['user_name']=trim($data['name']);
            $user['user_pass']=md5(base64_encode(trim( $data['pwd'] )));
            $user['user_email']=trim($data['email']);
            $user['reg_time']=time();
            $user['reg_ip']=$request->ip();
            $newid = HomeModel::addUser($user);
            $userInfo = HomeModel::getOneUser(['id'=>$newid]);
            session(['user'=>$userInfo]);
            // dd(session('user'));exit;
            // dd(session('user')->id);exit;
            // return redirect('backstage/index');
            return response()->json(['res'=>'1','msg'=>'註冊成功！','jumpUrl'=>'/user/index']);
        }
    }
    //檢查用戶名
    public function ckName(Request $request){
        $data = $request->input();
        $name = trim($data['name']);
        $count = CommonModel::getCount('user',['user_name'=>$name]);
        if($count>0){
            return response()->json(['res'=>'0','msg'=>'用戶名已被使用']);
        }else{
            return response()->json(['res'=>'1','msg'=>'可以使用']);
        }
    }
    //檢查郵箱
    public function ckEmail(Request $request){
        $data = $request->input();
        $email = trim($data['email']);
        $count = CommonModel::getCount('user',['user_email'=>$email]);
        if($count>0){
            return response()->json(['res'=>'0','msg'=>'郵箱賬號已被使用']);
        }else{
            return response()->json(['res'=>'1','msg'=>'可以使用']);
        }
    }
    // 找回密碼下壹步
    public function userNext(Request $request){
        $data = $request->input();
        // $name = trim($data['name']);
        $email = trim($data['email']);
        $code = trim($data['code']);
        
        if(empty($data['email'])){
            return response()->json(['res'=>'0','msg'=>'請輸入該賬號綁定的郵箱！']);
        }else{
            $count = CommonModel::getCount('user',['user_email'=>$email]);
            if($count == 0){
                return response()->json(['res'=>'0','msg'=>'該郵箱號未被註冊，請重新填寫！']);
            }
        }
        if(empty($data['code'])){
            return response()->json(['res'=>'0','msg'=>'請輸入驗證碼，如果沒有收到驗證碼請嘗試重新發送！']);
        }else{
            $peg = is_verify($email,$code,2,1800);
            if( $peg == false ){
                return response()->json(['res'=>'0','msg'=>'驗證碼輸入錯誤！請重新輸入驗證碼！']);
            }
        }
        return response()->json(['res'=>'1','msg'=>'驗證成功！']);
    }
    // 確定修改密碼
    public function userSure(Request $request){
        $data = $request->input();
        $pwd = $data['newpass'];
        $repwd = $data['new_repass'];
        if( empty($data['newpass']) ){
            return response()->json(['res'=>'0','msg'=>'請設置密碼！']);
        }elseif(strlen($pwd)<6){
            return response()->json(['res'=>'0','msg'=>'請輸入不小於6位數的字符或數字作為密碼！']);
        }
        if( $pwd!=$repwd){
            return response()->json(['res'=>'0','msg'=>'兩次輸入的密碼不壹致！']);
        }
        $password=md5(base64_encode(trim($pwd)));
        $email = $data['email'];
        // dd($email);
        // Session::reflash();
        // DB::connection()->enableQueryLog();
        $save = CommonModel::updateData('user',['user_email'=>$email],['user_pass'=>$password]);
        // $queries = DB::getQueryLog();
        // dd($queries);
        if($save){
            return response()->json(['res'=>'1','msg'=>'修改成功！','jumpUrl'=>'/']);
        }else{
            return response()->json(['res'=>'0','msg'=>'修改失敗！']);
        }
    }
    // 發送郵件
    public function sendEmail(Request $request){
        if($request->isMethod('POST')){
            $email = $request->input('email');
            $code = rand_string($email,6,1,$request->input('type'));
            $count = CommonModel::getCount('user',['user_email'=>$email]);
            Session::flash('code', $code);
            Session::flash('email', $email);
            if($request->input('type')==1){
                // 註冊
                if($count){
                    return response()->json(['res'=>0,'msg'=>'該郵箱已被使用無法獲取驗證碼！']);
                }
                $data = ['type'=>1,'code'=>$code,'email'=>$email];
                // Session::flash('code', $code);
                $send = Mail::send('home.public.mail',$data,function($message){
                    $to = Session::get('email');
                    $message->to($to)->subject('註冊驗證碼');
                });
                // dd($send);
            }elseif($request->input('type')==2){
                // 找回密碼
                if($count==0){
                    return response()->json(['res'=>0,'msg'=>'郵箱錯誤，該郵箱號未被使用！']);
                }
                // $code = rand_string($email);
                $data = ['type'=>2,'code'=>$code,'email'=>$email];
                
                // dd($email);
                $send = Mail::send('home.public.mail',$data,function($message){
                    $to = Session::get('email');
                    $message->to($to)->subject('找回密碼驗證碼');
                });
            }elseif($request->input('type')==3){
                $uid = session('user')->id;
                // 訂單提醒
                $order = UserModel::getOneOrder($request->input('id'));
                $user = CommonModel::getOne('user',['id'=>$uid],['family','name','user_email']);
                $weight = CommonModel::getField('product','weight',['id'=>$order->pid]);
                $order->weight = $weight;
                $data = ['type'=>3,'order'=>$order,'user'=>$user];
                $send = Mail::send('home.public.mail',$data,function($message){
                    $to = Session::get('email');
                    $message->to($to)->subject('至尊寶訂單通知');
                });
            }
            return response()->json(['res'=>1,'msg'=>'郵件發送成功，請登陸郵箱查看驗證碼，然後填入上面的文本框中！']);
        }
    }
    // 登陸驗證碼
    public function code(){
       $code = new Code;
       $code -> make();
    }
    public function loginOut(Request $request){
        // echo 123;exit;
        $request->session()->flush();
        $request->session()->regenerate();
        // session(['admin'=>null]);
        // echo '<script>top.location.href="https://'.$_SERVER['HTTP_HOST'].'/backstage/login";</script>';
        return redirect('/message')->with(['res'=>1,'msg'=>'已為您安全退出','url'=>'/']);
    }

}
